//
//  HTTPClient.swift
//  个人微博
//
//  Created by 一介布衣 on 16/2/27.
//  Copyright © 2016年 HUAMANLOU. All rights reserved.
//

import UIKit
import AFNetworking


// 网络请求方式
// 枚举在Swift中更加强大，可以枚举任何类型
enum HTTPMethod: String {
    case GET = "GET"
    case POST = "POST"
}

// 一般网络访问的工具类需要设计成单例
class HTTPClient: AFHTTPSessionManager {
    
    // 定义反转域名
    let domain = "com.baidu.data.error"
    
    static let sharedClient: HTTPClient = {
        let urlString = "https://api.weibo.com/"
        let url = NSURL(string: urlString)
        let tools = HTTPClient(baseURL: url)
        // 设置支持的解析类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    // TODO: 私有化构造函数
    
    // 网络请求方法的封装 GET + POST 
    func requestJSONDict(method: HTTPMethod, urlString:String,parameters:[String:AnyObject]?, finished:(dict:[String:AnyObject]?, error:NSError?)->()) {
        if method == .GET {
            // get请求
            GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
                guard let dict = result as? [String:AnyObject] else {
                    // 获取的数据不能够转换为字典类型数据
                    // 执行失败的回调
                    // 自定义错误信息
                    // domin：域名的翻转信息 cn.itcast
                    // 自定义错误码一般为负数或者大于10000
                    let myError = NSError(domain: self.domain, code: 10000, userInfo: [NSLocalizedDescriptionKey:"数据解析错误"])
                    finished(dict: nil, error: myError)
                    return
                }
                
                // 执行成功的回调
                finished(dict: dict, error: nil)
                
                }, failure: { (_, error) -> Void in
                        finished(dict: nil, error: error)
                    print(error)
            })
        
        }else {
            // post请求
            POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
                guard let dict = result as? [String:AnyObject] else {
                    let myError = NSError(domain: self.domain, code: 10000, userInfo: [NSLocalizedDescriptionKey:"数据解析错误"])
                    finished(dict: nil, error: myError)
                    return
                }
                
                // 执行成功的回调
                finished(dict: dict, error: nil)
                
                }, failure: { (_, error) -> Void in
                    finished(dict: nil, error: error)
                    print(error)
            })
        
        
        
        }
    }
}








